/**
 * @author LYJ
 * Created by Administrator on 2018/2/28 0028.
 */
;(function($, window, document,undefined) {
    var defaultParams = {
        defaultImage: "img/selectImage/emptyImg.png"
    };

    var ShowImage = function ($element,options) {
        this.$element = $element;
        this.defaults = defaultParams;
        this.options = this.$element.extend({}, this.defaults, options);
        this.init();
    };

    ShowImage.prototype = {
        init:function () {
            var element = this.$element;
            var html = '' +
                '<img class="selectImg" src="">';
            element.after(html);

            var $selectImg = $(".selectImg");
            $selectImg.on("click",function () {
                element.click();
            });
            element.on("change",function () {
                var file = element[0].files[0];
                $selectImg.attr("src",file ? getUrl(file) : "");
            });
        },
        getImg: function () {
            return this.$element.next("img");
        },
        setImg: function (rootPath,path) {
            if(!path || path == ""){
                this.getImg().attr("src",rootPath+this.options.defaultImage);
            }else{
                this.getImg().attr("src",rootPath+path);
            }

        }
    };

    //在插件中使用Beautifier对象
    $.fn.selectImage = function(options) {
        var $this = $(this);
        var data = $this.data('bs.showImage');
        if(!data){
            data = new ShowImage($this,options);
            $this.data('bs.showImage',data);
        }
        return data;
    };

    var getUrl = function (file) {
        var url = null ;
        if (window.createObjectURL!=undefined) { // basic
            url = window.createObjectURL(file) ;
        } else if (window.URL!=undefined) { // mozilla(firefox)
            url = window.URL.createObjectURL(file) ;
        } else if (window.webkitURL!=undefined) { // webkit or chrome
            url = window.webkitURL.createObjectURL(file) ;
        }
        return url ;
    }
})(jQuery, window, document);